package app;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.menhoo.toollibrary.android.log.Log;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.AppApplication;
import application.HttpUrlConstant;
import custom.PinnedSectionListView;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.EmployeeItemDBModel;

/**
 * 部门选择
 * Created by yanglei on 15/10/7.
 */
public class AddressBookDeptSelector extends AppActivity {
    private static final String TAG = "AddressBookDeptSelector";
    PinnedSectionListView list = null;
    deptAdapter adapter;
    String deptID = "0", title = "";


    private boolean addPadding = false;
    private boolean isShadowVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.address_book_dept_selector_activity);


        try {
            deptID = getIntent().getExtras().getString("deptID");
        } catch (Exception ex) {
            deptID = "0";
        }
        try {
            title = getIntent().getExtras().getString("title");
        } catch (Exception ex) {
            title = "部门";
        }

        list = (PinnedSectionListView) findViewById(R.id.PinnedSectionList);
        list.setShadowVisible(isShadowVisible);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //如果id是-1说明这个是Header 或者  Footer
                if (id == -1) {
                    return;
                }
                EmployeeItemDBModel item = (EmployeeItemDBModel) parent.getAdapter().getItem(position);

                if (item.type == EmployeeItemDBModel.ITEM) {

                    if (item.DeptID == null || item.DeptID.equalsIgnoreCase("")) {
                        //empl
                        Intent it = new Intent(AddressBookDeptSelector.this, ContactInfo.class);
                        it.putExtra("emplID", item.EmplID);
                        startActivity(it);
                    } else {
                        //dept
                        Intent it = new Intent(AddressBookDeptSelector.this, AddressBookDeptSelector.class);
                        it.putExtra("deptID", item.DeptID);
                        it.putExtra("title", item.Name);
                        startActivity(it);
                    }

                }

            }
        });

        setTitle(title);
        hideContent();

        initializePadding();

        initializeAccountList(deptID);
    }

    private void initializePadding() {
        float density = getResources().getDisplayMetrics().density;
        int padding = addPadding ? (int) (16 * density) : 0;

        list.setPadding(padding, 0, padding, 0);
    }


    private void initializeAccountList(final String deptID) {

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("__session__", AppApplication.getSession());
        params.addQueryStringParameter("deptid", deptID);
        httpGet(HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.AccountList), params, new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                try {
                    Log.i(TAG, result);
                    JSONObject jsonResult = new JSONObject(result);
                    if (jsonResult.getBoolean("Succeed")) {
                        List<EmployeeItemDBModel> listData = new ArrayList<EmployeeItemDBModel>();
                        String CurrentDeptName = jsonResult.getString("CurrentDeptName");
                        JSONArray Depts = jsonResult.getJSONArray("Depts");
                        JSONArray Empls = jsonResult.getJSONArray("Empls");

                        if (Depts.length() > 0) {
                            listData.add(new EmployeeItemDBModel(EmployeeItemDBModel.SECTION, "部门"));
                        }
                        for (int i = 0; i < Depts.length(); i++) {
                            JSONObject deptObj = Depts.getJSONObject(i);
                            String ID = deptObj.getString("ID");
                            String Name = deptObj.getString("Name");

                            EmployeeItemDBModel item = new EmployeeItemDBModel();
                            item.DeptID = ID;
                            item.EmplID = null;
                            item.Name = Name;
                            item.type = EmployeeItemDBModel.ITEM;
                            listData.add(item);
                        }
                        if (Empls.length() > 0) {
                            listData.add(new EmployeeItemDBModel(EmployeeItemDBModel.SECTION, "人员"));
                        }
                        for (int i = 0; i < Empls.length(); i++) {
                            JSONObject emplObj = Empls.getJSONObject(i);
                            String ID = emplObj.getString("ID");
                            String Name = emplObj.getString("Name");
                            String DeptID = emplObj.getString("DeptID");
                            String Sex = emplObj.getString("Sex");

                            EmployeeItemDBModel item = new EmployeeItemDBModel();
                            item.EmplID = ID;
                            item.DeptID = null;
                            item.Name = Name;
                            item.type = EmployeeItemDBModel.ITEM;
                            listData.add(item);
                        }
                        if (listData.size() > 0) {
                            adapter = new deptAdapter(listData);
                            list.setAdapter(adapter);
                            showContent();
                        } else {
                            showEmpty();
                        }

                    } else {
                        showError(new IReturnObject<String>() {
                            @Override
                            public void returnResult(String result) {
                                initializeAccountList(deptID);
                            }
                        });
                    }


                } catch (JSONException e) {
                    showError(new IReturnObject<String>() {
                        @Override
                        public void returnResult(String result) {
                            initializeAccountList(deptID);
                        }
                    });
                }
            }
        });
    }

    public class deptAdapter extends BaseAdapter implements PinnedSectionListView.PinnedSectionListAdapter {

        private List<EmployeeItemDBModel> data = new ArrayList<EmployeeItemDBModel>();

        public deptAdapter(List<EmployeeItemDBModel> list) {

            int sectionPosition = -1, listPosition = 0;
            for (EmployeeItemDBModel section : list) {
                if (section.type == EmployeeItemDBModel.SECTION) {
                    sectionPosition++;
                }
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;

            }
            data = list;

        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public EmployeeItemDBModel getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            EmployeeItemDBModel item = getItem(position);

            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                if (item.type == EmployeeItemDBModel.ITEM) {
                    convertView = getLayoutInflater().inflate(R.layout.adapter_item_address_book_dept, null);
                    viewHolder.img = (ImageView) convertView.findViewById(R.id.imageView1);
                } else {
                    convertView = getLayoutInflater().inflate(R.layout.adapter_item_address_book_only_text, null);
                }
                viewHolder.content = (TextView) convertView.findViewById(R.id.textView1);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            if (item.type == EmployeeItemDBModel.ITEM) {

                if (item.EmplID != null && !item.EmplID.equalsIgnoreCase("")) {
                    Map<String, String> parm = new HashMap<String, String>();
                    parm.put("emplid", item.EmplID);
                    getBitmapLoader().display(viewHolder.img, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.doShowPhoto,
                            parm));
                } else {
                    viewHolder.img.setImageResource(R.mipmap.group_chat);
                }

            }

            viewHolder.content.setText(item.Name);

            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return getItem(position).type;
        }

        @Override
        public boolean isItemViewTypePinned(int viewType) {
            return viewType == EmployeeItemDBModel.SECTION;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

    }

    class ViewHolder {
        TextView content;
        ImageView img;
    }


}
